import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_zvt_plugin/zvt/index.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ZVT Payment Plugin Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'ZVT Payment Plugin Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _logText = '';
  bool _isProcessing = false;
  String? _receiptContent;

  final deviceIp = "192.168.50.125";
  final devicePort = 20007;
  final currencyIsoCode = 203;
  // final deviceIp = "192.168.50.113";
  // final devicePort = 20008;
  // final currencyIsoCode = 978;
  void _addLog(String message) {
    debugPrint('${DateTime.now().toString().substring(11, 19)}: $message\n');
    setState(() {
      _logText += '${DateTime.now().toString().substring(11, 19)}: $message\n';
    });
  }

  Future<void> _testZVTConnection() async {
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });

    double? amount = await showDialog<double>(
      context: context,
      builder: (context) {
        String input = '2.15';
        return AlertDialog(
          title: const Text('输入交易金额'),
          content: TextField(
            autofocus: true,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            decoration: const InputDecoration(hintText: '请输入金额，如2.15'),
            controller: TextEditingController(text: input),
            onChanged: (value) => input = value,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final parsed = double.tryParse(input);
                if (parsed != null && parsed > 0) {
                  Navigator.of(context).pop(parsed);
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
    if (amount == null) {
      setState(() {
        _isProcessing = false;
      });
      return;
    }

    try {
      _addLog('开始授权交易...');
      final authResult = await zvtPayment.authorization(
        amount: amount,
        timeout: 60 * 3,
        maxStatusInfos: 3,
        currencyIsoCode: currencyIsoCode,
        codeLog: (log) {
          _addLog('交易: $log');
        },
      );
      _addLog('授权交易成功: ${json.encode(authResult.toJson())}');
      if (authResult.receipt?.printContent != null &&
          authResult.receipt!.printContent.trim().isNotEmpty) {
        setState(() {
          _receiptContent =
              authResult.receipt!.printContent.replaceAll('\n', '\n');
        });
      }
    } catch (e) {
      _addLog('错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testReversal() async {
    String? batchNumber = await showDialog<String>(
      context: context,
      builder: (context) {
        String input = '';
        return AlertDialog(
          title: const Text('输入要取消的交易流水号4位'),
          content: TextField(
            autofocus: true,
            decoration: const InputDecoration(hintText: '请输入原交易流水号4位'),
            onChanged: (value) => input = value,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(input),
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
    if (batchNumber == null || batchNumber.trim().isEmpty) return;
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });

    try {
      _addLog('开始取消交易...');
      final reversalResult = await zvtPayment.reversal(
        batchNumber: batchNumber.trim(),
        codeLog: (log) {
          _addLog('取消: $log');
        },
      );
      _addLog('取消交易成功: ${json.encode(reversalResult.toJson())}');
      if (reversalResult.receipt?.printContent != null &&
          reversalResult.receipt!.printContent.trim().isNotEmpty) {
        setState(() {
          _receiptContent =
              reversalResult.receipt!.printContent.replaceAll('\n', '\n');
        });
      }
    } catch (e) {
      _addLog('取消交易错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testRefund() async {
    double? amount = await showDialog<double>(
      context: context,
      builder: (context) {
        String input = '1.50';
        return AlertDialog(
          title: const Text('输入退款金额'),
          content: TextField(
            autofocus: true,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            decoration: const InputDecoration(hintText: '请输入退款金额，如10.00'),
            controller: TextEditingController(text: input),
            onChanged: (value) => input = value,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final parsed = double.tryParse(input);
                if (parsed != null && parsed > 0) {
                  Navigator.of(context).pop(parsed);
                }
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
    if (amount == null) {
      setState(() {
        _isProcessing = false;
      });
      return;
    }

    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });

    try {
      _addLog('开始退款交易...');
      _addLog('退款金额: $amount');
      final refundResult = await zvtPayment.refund(
        amount: amount,
        timeout: 60 * 3,
        currencyIsoCode: currencyIsoCode,
        codeLog: (log) {
          _addLog('退款: $log');
        },
      );
      _addLog('退款交易成功: ${json.encode(refundResult.toJson())}');
      if (refundResult.receipt?.printContent != null &&
          refundResult.receipt!.printContent.trim().isNotEmpty) {
        setState(() {
          _receiptContent =
              refundResult.receipt!.printContent.replaceAll('\n', '\n');
        });
      }
    } catch (e) {
      _addLog('退款交易错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testEndOfDay() async {
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });
    try {
      _addLog('开始日结...');
      final result = await zvtPayment.endOfDay(
        codeLog: (log) {
          _addLog('日结: $log');
        },
      );
      _addLog('日结完成: ${json.encode(result.toJson())}');
      if (result.receipt?.printContent != null &&
          result.receipt!.printContent.trim().isNotEmpty) {
        setState(() {
          _receiptContent = result.receipt!.printContent.replaceAll('\n', '\n');
        });
      }
    } catch (e) {
      _addLog('日结错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  // 新增终止交易测试方法
  Future<void> _testAbort() async {
    try {
      _addLog('开始终止交易...');
      final result = await zvtPayment.abort(
        codeLog: (log) {
          _addLog('终止: $log');
        },
      );
      _addLog('终止交易完成: \\${json.encode(result.toJson())}');
      setState(() {
        _isProcessing = true;
        _logText = '';
        _receiptContent = null;
      });
    } catch (e) {
      _addLog('终止交易错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testRegistration() async {
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });
    try {
      _addLog('开始注册配置...');
      final result = await zvtPayment.registration(
        currencyIsoCode: currencyIsoCode,
        sendStatusInfomation: true,
        printManagerReceipt: false,
        printPaymentReceipt: false,
        allowStartPaymenttTerminal: true,
        allowAdminPaymentTerminal: true,
        codeLog: (log) {
          _addLog('注册: $log');
        },
      );
      _addLog('注册配置完成: ${json.encode(result.toJson())}');
    } catch (e) {
      _addLog('注册配置错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testLogOff() async {
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });
    try {
      _addLog('开始注销配置...');
      final result = await zvtPayment.logOff(
        codeLog: (log) {
          _addLog('注销: $log');
        },
      );
      _addLog('注销配置完成: ${json.encode(result.toJson())}');
    } catch (e) {
      _addLog('注销配置错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  Future<void> _testRepeatReceipt() async {
    setState(() {
      _isProcessing = true;
      _logText = '';
      _receiptContent = null;
    });
    try {
      _addLog('开始打印上次交易收据...');
      final result = await zvtPayment.repeatReceipt(
        codeLog: (log) {
          _addLog('重打收据: $log');
        },
      );
      _addLog('打印上次交易收据完成: ${json.encode(result.toJson())}');
      if (result.receipt?.printContent != null &&
          result.receipt!.printContent.trim().isNotEmpty) {
        setState(() {
          _receiptContent = result.receipt!.printContent.replaceAll('\n', '\n');
        });
      }
    } catch (e) {
      _addLog('打印上次交易收据错误: $e');
    } finally {
      setState(() {
        _isProcessing = false;
      });
    }
  }

  // 获取ZVTPayment实例
  final zvtPayment = ZVTPayment.current();
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _addLog('开始测试ZVT连接...');

      zvtPayment.setConnectIP(ip: deviceIp, port: devicePort);
      _addLog('连接参数设置完成: $deviceIp:$devicePort');
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            ElevatedButton(
              onPressed: _isProcessing ? null : _testZVTConnection,
              child: Text(_isProcessing ? '处理中...' : '测试ZVT连接'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testReversal,
              child: Text(_isProcessing ? '处理中...' : '取消交易'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testRefund,
              child: Text(_isProcessing ? '处理中...' : '退款交易'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testEndOfDay,
              child: Text(_isProcessing ? '处理中...' : '日结测试'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _testAbort,
              child: Text(_isProcessing ? '处理中...' : '终止交易'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testRegistration,
              child: Text(_isProcessing ? '处理中...' : '注册配置'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testLogOff,
              child: Text(_isProcessing ? '处理中...' : '注销配置'),
            ),
            const SizedBox(height: 8),
            ElevatedButton(
              onPressed: _isProcessing ? null : _testRepeatReceipt,
              child: Text(_isProcessing ? '处理中...' : '打印上次交易'),
            ),
            const SizedBox(height: 16),
            if (_receiptContent != null && _receiptContent!.isNotEmpty) ...[
              const Text('小票内容（可复制）：',
                  style: TextStyle(fontWeight: FontWeight.bold)),
              SizedBox(
                height: 180,
                child: TextField(
                  controller:
                      TextEditingController(text: _receiptContent ?? ''),
                  maxLines: null,
                  readOnly: true,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 13),
                  decoration: InputDecoration(
                    border: const OutlineInputBorder(),
                    suffixIcon: IconButton(
                      icon: const Icon(Icons.copy),
                      tooltip: '复制',
                      onPressed: () {
                        Clipboard.setData(
                            ClipboardData(text: _receiptContent ?? ''));
                        ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('小票内容已复制')));
                      },
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 16),
            ],
            Expanded(
              child: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: SingleChildScrollView(
                  child: Text(
                    _logText.isEmpty ? '点击按钮开始测试...' : _logText,
                    style:
                        const TextStyle(fontFamily: 'monospace', fontSize: 12),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
